import os
import datetime
import time
from conf.const import *
from django.db import connection
from asgiref.sync import sync_to_async
import asyncio
import django
import pymysql
import re

pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()
os.environ['DJANGO_ALLOW_ASYNC_UNSAFE'] = 'true'   # 允许异步模式

# 打开 数据库配置 文件 （！！！数据库配置同名变量删除）
with open(ENV_FILE_PATH, "r") as file:
    # 读取文件内容
    content = file.read()
    # 在文件内容中查找变量
    DATABASE_ENGINE = None
    DATABASE_NAME = None
    DATABASE_USER = None
    DATABASE_PASSWORD = None
    DATABASE_HOST = None
    DATABASE_PORT = None
    # 使用正则表达式匹配变量
    pattern = r'DATABASE_ENGINE\s*=\s*"(.+)"'
    match_engine = re.search(pattern, content)
    if match_engine:
        DATABASE_ENGINE = match_engine.group(1)

    pattern = r'DATABASE_NAME\s*=\s*\'(.+)\''
    match_name = re.search(pattern, content)
    if match_name:
        DATABASE_NAME = match_name.group(1)

    pattern = r'DATABASE_HOST\s*=\s*"(.+)"'
    match_host = re.search(pattern, content)
    if match_host:
        DATABASE_HOST = match_host.group(1)

    pattern = r'DATABASE_PORT\s*=\s*(\d+)'
    match_port = re.search(pattern, content)
    if match_port:
        DATABASE_PORT = int(match_port.group(1))

    pattern = r'DATABASE_USER\s*=\s*"(.+)"'
    match_user = re.search(pattern, content)
    if match_user:
        DATABASE_USER = match_user.group(1)

    pattern = r'DATABASE_PASSWORD\s*=\s*"(.+)"'
    match_password = re.search(pattern, content)
    if match_password:
        DATABASE_PASSWORD = match_password.group(1)

    print("DATABASE_ENGINE:", DATABASE_ENGINE)
    print("DATABASE_NAME:", DATABASE_NAME)
    print("DATABASE_HOST:", DATABASE_HOST)
    print("DATABASE_PORT:", DATABASE_PORT)
    print("DATABASE_USER:", DATABASE_USER)
    print("DATABASE_PASSWORD:", DATABASE_PASSWORD)    

# 设置数据库连接信息
DATABASES = {
    'default': {
      "ENGINE": DATABASE_ENGINE,
        "NAME": DATABASE_NAME,
        "USER": DATABASE_USER,
        "PASSWORD": DATABASE_PASSWORD,
        "HOST": DATABASE_HOST,
        "PORT": DATABASE_PORT,
    }
}

# 配置 Django
settings_dict = {
    'DATABASES': DATABASES,
}

django.conf.settings.configure(**settings_dict)

# 初始化 Django
django.setup()

# 循环执行脚本
while True:
    # 图片目录
    root_dir = BASE_FILE_PATH

    # 打开 const 文件
    with open(CONST_FILE_PATH, "r") as file:
        # 读取文件内容
        file_content = file.read()

        # 在文件内容中查找变量
        INTERVAL_TIME = None
        SAVE_PHOTO_DAY = None

        # 使用正则表达式或其他方法从文件内容中提取目标变量的值
        match_INTERVAL_TIME = re.search(r"INTERVAL_TIME\s*=\s*(.*)", file_content)
        if match_INTERVAL_TIME:
            target_variable = match_INTERVAL_TIME.group(1)
        
        match_SAVE_PHOTO_DAY = re.search(r'SAVE_PHOTO_DAY\s*=\s*(\w+)', file_content)
        if match_SAVE_PHOTO_DAY:
            del_day = int(match_SAVE_PHOTO_DAY.group(1))

    # 该脚本执行间隔
    interval_time = int(target_variable)
    # 获取当前日期
    current_date = datetime.datetime.now().date()

    # 计算7天前的日期
    seven_days_ago = current_date - datetime.timedelta(days=del_day)
    # 遍历目录中的文件夹
    for dir_name in os.listdir(root_dir):
        dir_path = os.path.join(root_dir, dir_name)

        # 检查文件夹名称是否符合日期格式
        try:
            dir_date = datetime.datetime.strptime(dir_name, "%Y-%m-%d").date()
        except ValueError:
            # 如果文件夹名称不符合日期格式，跳过该文件夹
            continue

        # 检查文件夹日期是否早于7天前
        if dir_date < seven_days_ago:
            # 删除文件夹及其内容
            os.system("rm -rf " + dir_path)
            # 删除数据表内容
            # 异步执行删除数据库操作
            async def delete_from_database(name):
                sql = 'DELETE FROM dvadmin_defect_data_main WHERE Date(create_datetime) = %s;'
                await sync_to_async(connection.cursor().execute)(sql, name)
            asyncio.run(delete_from_database(dir_name))
    # 设置运行间隔
    time.sleep(interval_time)
    print("sleep")